import React, { useState, useRef, FC } from 'react';
import type { ProFormInstance } from '@ant-design/pro-form';
import { EditableProTable } from '@ant-design/pro-table';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProForm, {
  StepsForm,
  ProFormDigit,
  ProFormText,
  ProFormSelect,
} from '@ant-design/pro-form';
import { Modal, message, Button, Row, Col, Card, Result } from 'antd';
import {
  getLocalStorageInfo,
  setLocalStorageInfo,
} from '@/utils/localStorageInfo';
import { lssueToken } from './service';
import { getContractProtocols } from '@/services/services';
import type { ContractProtocolType, ContractProtocolInfosType } from './data.d';
import { editColumnsData, DataSourceType } from './data';
import styles from './Issue.css';

type BeforeIssuePropsType = {
  setIsIssue: any;
};

const BeforeIssue: FC<BeforeIssuePropsType> = ({ setIsIssue }) => {
  const editProColumns: ProColumns<DataSourceType>[] = editColumnsData;
  // 获取表单
  const formRef = useRef<ProFormInstance>();
  // 控制发行模态框
  const [isIssueModal, setIsIssueModal] = useState(false);
  // 倒计时
  const [countDown, setCountDown] = useState(3);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  // 合约规则列表
  const [contractProtocol, setContractProtocol] = useState<
    ContractProtocolType[]
  >([]);
  // 表单信息
  const [formInfo, setFormInfo] = useState({});

  /**
   * 获取合约模板
   */
  const getContract = async () => {
    let res = await getContractProtocols({});
    console.log(res);
    setContractProtocol(
      res.data.map((item: ContractProtocolInfosType) => {
        const { protocolName: label, serialNo: value } = item;
        return {
          label,
          value,
        };
      }),
    );
  };

  /**
   * 表格操作列
   */ const actionRender: any = (text: any, record: any, _, action) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      <li>
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.code);
          }}
        >
          编辑
        </a>
        <em className="ant-list-item-action-split"></em>
      </li>
      <li>
        <a
          key="delete"
          onClick={() => {
            setDataSource(
              dataSource.filter((item) => item.code !== record.code),
            );
          }}
        >
          删除
        </a>
      </li>
    </ul>
  );

  editProColumns.forEach((item) => {
    item.valueType === 'option' ? (item.render = actionRender) : undefined;
  });

  // 发行
  const toIssue = () => {
    getContract();
    setIsIssueModal(true);
  };

  return (
    <>
      <Card className={styles.unIssue}>
        {/* 未发行展示 */}
        <Row>
          <Col span={12} style={{ paddingTop: 100, paddingBottom: 100 }}>
            <h1 className={styles.title}>DaoBook</h1>
            <h2 className={styles.description}>一站式Dao组织低代码搭建平台</h2>
            <h3 className={styles.subDescription}>
              帮助用户构建新的生产关系，实现共创共治共享
            </h3>
            <div className={styles.IssueBtn}>
              <Button
                type="primary"
                shape="round"
                size="large"
                onClick={toIssue}
              >
                发行
              </Button>
            </div>
          </Col>
          <Col span={12} style={{ paddingTop: 60, paddingBottom: 60 }}>
            <img
              src={require('../../../assets/issue.jpg')}
              alt=""
              style={{ width: '100%', height: '100%' }}
            />
          </Col>
        </Row>
      </Card>
      {/* 发行模态框 */}
      <StepsForm
        formRef={formRef}
        //  完成回调 value为填写的表单的信息
        onFinish={async (values) => {
          // 确认发行
          setIsIssue(true);
          // console.log(values);
          // 关闭模态框
          setIsIssueModal(false);
          // true最后一步重置表单，回到第一步
          return true;
        }}
        onCurrentChange={(val) => {
          if (val === 2) {
            setTimeout(() => {
              formRef?.current?.submit();
              setIsIssueModal(false);
            }, 3000);
            for (let i = 0; i < 3; i++) {
              setTimeout(
                function (j) {
                  setCountDown(3 - j);
                },
                i * 1000,
                i,
              );
            }
          }
        }}
        // 表单验证规则
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        // 自定义整个表单区域，返回的 dom 在表单的外部
        stepsFormRender={(dom, submitter) => {
          return (
            <Modal
              title="发行"
              width={900}
              onCancel={() => setIsIssueModal(false)}
              visible={isIssueModal}
              footer={submitter}
              destroyOnClose
            >
              {dom}
            </Modal>
          );
        }}
        // 自定义按钮
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <Button type="primary" onClick={() => props.onSubmit?.()}>
                  下一步 {'>'}
                </Button>
              );
            }

            if (props.step === 1) {
              return [
                <Button key="pre" onClick={() => props.onPre?.()}>
                  上一步
                </Button>,
                <Button
                  type="primary"
                  key="goToTree"
                  onClick={() => props.onSubmit?.()}
                >
                  发行
                </Button>,
              ];
            }

            return null;
          },
        }}
      >
        {/* 一 发行信息录入*/}
        <StepsForm.StepForm
          name="base"
          title="发行信息"
          onFinish={async (values) => {
            setFormInfo({
              ...formInfo,
              ...values,
            });
            return true;
          }}
        >
          <ProFormText
            name="name"
            label="名称"
            tooltip="只能输入英文名称"
            placeholder="请输入英文名称"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="symbol"
            label="积分标识"
            placeholder="请输入积分标识"
            rules={[{ required: true }]}
          />
          <ProFormDigit
            name="totalSupply"
            label="总发行量"
            placeholder="请输入总发行量"
            rules={[{ required: true }]}
          />
          <ProFormDigit
            name="decimals"
            label="小数位数"
            placeholder="请输入小数位数"
            rules={[{ required: true }]}
          />
          {/* 合约模板 */}
          <ProFormSelect
            rules={[{ required: true }]}
            options={contractProtocol}
            name="contractProtocolNo"
            label="合约协议"
          />
        </StepsForm.StepForm>
        {/* 二 选择配置*/}
        <StepsForm.StepForm
          name="token"
          title="token分配"
          onFinish={async (values) => {
            if (!dataSource[0]) {
              message.info('请填写团队信息');
              return false;
            }
            let a: number = 0;
            dataSource.forEach((item) => (a += item.ratio));
            if (a !== 100) {
              message.info('团队分配相加应为100');
              return false;
            }
            console.log({
              ...formInfo,
              tokenDistribution: dataSource.map((item) => {
                let { code, name, ratio } = item;
                return { code, name, ratio };
              }),
            });

            let customerNo = getLocalStorageInfo('customerInfo').customerNo;
            let res = await lssueToken({
              ...formInfo,
              customerNo,
              tokenDistribution: dataSource.map((item) => {
                let { code, name, ratio } = item;
                return { code, name, ratio };
              }),
            });
            console.log(res);
            if (res.code === '000000') {
              console.log(res);
              let tenantDao = getLocalStorageInfo('tenantDao');
              tenantDao.hasToken = '1';
              setLocalStorageInfo('tenantDao', tenantDao);
              message.success('发行成功');
              return true;
            }
          }}
        >
          {/* 可编辑列表 */}
          <EditableProTable<DataSourceType>
            columns={editProColumns}
            rowKey="id"
            recordCreatorProps={{
              position: 'bottom',
              // 每次新增的时候需要Key
              record: () => ({ id: new Date() }),
            }}
            value={dataSource}
            onChange={setDataSource}
          />
        </StepsForm.StepForm>
        {/* 三 铸造完成*/}
        <StepsForm.StepForm name="time" title="发行完成">
          <Result
            status="success"
            title="发行成功！"
            subTitle={`欢迎使用Bigan数字资产管理平台`}
          />
          <span
            style={{
              display: 'inline-block',
              width: '100%',
              textAlign: 'center',
            }}
          >
            {countDown}秒后退出
          </span>
        </StepsForm.StepForm>
      </StepsForm>
    </>
  );
};

export default BeforeIssue;
